/**
 * 
 */
package com.jie.eclipse.pan.utils;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.debug.internal.ui.views.console.ProcessConsole;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.MessageConsole;
import org.eclipse.ui.console.MessageConsoleStream;

import com.jie.eclipse.pan.console.ConsoleFactory;
import com.jie.eclipse.pan.dao.QMDao;
import com.jie.eclipse.pan.data.BaseDataEntity;

/**
 * @author yanjie
 *
 * 2011/10/8 下午4:02:35
 */
public class Utils {
	public static void print(String message) {  
		try {
		    IConsole console = ConsoleFactory.getConsole();
		    if(console == null){
		    	System.out.println(message);
		    }else{
			    if(console instanceof MessageConsole){
			    	MessageConsoleStream printer = ((MessageConsole)console).newMessageStream();
			    	printer.setActivateOnWrite(true);  
			 	    printer.println(message );  
			    }if(console instanceof ProcessConsole){
			    	ProcessConsole pConsole = ((ProcessConsole)console);
					pConsole.newOutputStream().write(message);
					pConsole.newOutputStream().write("\r\n");
					
			    }
		    }
		} catch (Exception e) {
			e.printStackTrace();
		}
	    
	    
	   
	} 
	  /**
     * 格式化日期(yyyy/MM/dd).
     * 
     * @param date 傳入的日期
     * @return 格式化後的日期
     */
    public String formatDate(Date date) {
        String result = "";
        if (date != null) {
            result = new SimpleDateFormat("yyyy/MM/dd").format(date);
            if (result.equals("1900/01/01")) {
                result = "";
            }
        }
        return result;
    }
    
    /**
     * 格式化日期(yyyy/MM/dd hh:mm:ss).
     * 
     * @param date 傳入的日期
     * @return 格式化後的日期
     */
    public String formatDateTime(Date date) {
        String result = "";
        if (date != null) {
            result = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss").format(date);
            if (result.equals("1900/01/01")) {
                result = "";
            }
        }
        return result;
    }
    
    /**
     * @param pattern 日期格式
     * @param date 傳入的日期
     * @return 格式化後的日期
     * @author yanjie
     */
    public String formatDateTimes(Date date,String pattern) {
        String result = "";
        if (date != null) {
           result = new SimpleDateFormat(pattern).format(date);
           if (result.equals("1900/01/01")) {
                      result = "";
           }
        }
        return result;
    }
    
	/**
     * 放 Connection 的容器.
     */
    private Map<String, Connection> connPot = new HashMap<String, Connection>();
    /**
     * 放 Statement 的容器.
     */
    private List<PreparedStatement> stmtPot = new ArrayList<PreparedStatement>();
    /**
     * 放 ResultSet 的容器.
     */
    private List<ResultSet> rsPot = new ArrayList<ResultSet>();
    
    private boolean autoCommit = true;
	/**
     * 從 rs 裡面取得指定欄位的 String 資料.
     * 
     * @param rs 傳送過來的 rs.
     * @param colName 欄位名稱.
     * @return 該筆資料 value.
     * @throws Exception
     */
    public String getRsString(ResultSet rs, String colName) throws Exception {
        String result = "";
        try {
            if (rs.getString(colName) != null) {
                result = rs.getString(colName).trim().replaceAll("<","&lt;");	//簡單防止數據庫xxl漏洞
            }
        } catch (Exception ex) {
            StringBuffer msg = new StringBuffer(this.getClass().getName()).append(" occurs error : ").append(ex.getMessage());
            throw new Exception(msg.toString());
        }
        return result;
    }

    /**
     * 從 rs 裡面取得指定欄位的 String 資料.
     * 
     * @param rs 傳過來的 rs.
     * @param col 第幾個欄位.
     * @return 該筆資料 value.
     * @throws Exception
     */
    public String getRsString(ResultSet rs, int col) throws Exception {
        String result = "";
        try {
            if (rs.getString(col) != null) {
                result = rs.getString(col).trim().replaceAll("<","&lt;");	//簡單防止數據庫xxl漏洞
            }
        } catch (Exception ex) {
            StringBuffer msg = new StringBuffer(this.getClass().getName()).append(" occurs error : ").append(ex.getMessage());
            throw new Exception(msg.toString());
        }
        return result;
    }
    
    /**
     * 查詢 sql 語句.
     * @param serverName
     * @param sql
     * @return
     */
    public ResultSet executeQuery(String serverName, String sql) throws Exception {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            // 檢查是否有連線存在 conns, 如果沒有, 建一個放進去. 
            if ((conn = (Connection) connPot.get(serverName)) == null) {
                conn = getConnection(serverName);
                connPot.put(serverName, conn);
            }
            conn.setAutoCommit(this.autoCommit);
            // 取得 statement.
            //stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            stmt = conn.prepareStatement(sql);
            stmtPot.add(stmt);
            // 取得 rs.
            rs = stmt.executeQuery();
            
            rsPot.add(rs);
        } catch (Exception e) {
        	e.printStackTrace();
            // rollback();
            System.out.println("- Utils.executeQuery() 發生錯誤 !!");
            System.out.println("- Server Name : " + serverName);
            System.out.println("- SQL : " + sql);
            this.cleanUp();
            throw e;
        }
        return rs;
    }

    /**
     * 執行 sql 語句.
     * @param serverName
     * @param sql
     * @return
     */
    public int executeUpdate(String serverName, String sql) throws Exception {
        Connection conn = null;
        PreparedStatement stmt = null;
        int result = 0;
        try {
            // 檢查是否有連線存在 conns, 如果沒有, 建一個放進去.
            if ((conn = (Connection) connPot.get(serverName)) == null) {
                conn = getConnection(serverName);
                connPot.put(serverName, conn);
            }
            conn.setAutoCommit(this.autoCommit);
            // 取得 statement.
            stmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            stmtPot.add(stmt);
            // 執行.
            result = stmt.executeUpdate();
        } catch (Exception e) {
            // rollback();
            System.out.println("===== Utils.executeUpdate() 發生錯誤 !!");
            System.out.println("- Server Name : " + serverName);
            System.out.println("- SQL : " + sql);
            this.cleanUp();
            throw e;
        }
        return result;
    }
    
    public Connection getConnection(String serverName) throws Exception{
    	Connection conn = null;
    	String user = "sa";
    	String password = "";
    	BaseDataEntity config = QMDao.getInstance().getPanDataSourceMap().get(serverName);
    	
    	password = config.gpsv("pwd");
    	
    	Class.forName("net.sourceforge.jtds.jdbc.Driver");
    	conn = DriverManager.getConnection(
    			"jdbc:jtds:sqlserver://"+config.gpsv("ip")+":1433/master", user, password);
        return conn;
    }
    /**
     * 清除 rs, stmt, conn 的資料庫相關物件.
     */
    public void cleanUp() {
        try {
            // commit();
            // 清除rs.
            if (rsPot != null) {
                for (ResultSet rs : rsPot) {
                    if (rs != null) {
                        rs.close();
                    }
                }
                rsPot.clear();
            }
            // 清除stmt.
            if (stmtPot != null) {
                for (PreparedStatement stmt : stmtPot) {
                    if (stmt != null) {
                        stmt.close();
                    }
                }
                stmtPot.clear();
            }
            // 清除連線.
            if (connPot != null) {
                for (Connection conn : connPot.values()) {
                    if (conn != null && !conn.isClosed()) {
                        conn.close();
                    }
                }
                connPot.clear();
            }
        } catch (Exception e) {
            // rollback();
            System.out.println("\n- " + formatDateTime(new Date()));
            System.out.println("- Utils.cleanUp() 發生錯誤 !!");
            e.printStackTrace();
        }
    }
    
    /**
     * @param char 
     * @return boolean
     */
    private boolean isChinese(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
				|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
				|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
				|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
			return true;
		}
		return false;
	}

	/**
	 * @param String
	 * @return boolean
	 */
	public boolean isChinese(String strName) {
		char[] ch = strName.toCharArray();
		for (int i = 0; i < ch.length; i++) {
			char c = ch[i];
			if (isChinese(c)) {
				return true;
			}
		}
		return false;
	}
    
}